/*
 * @Author: JiangSheng 87789771@qq.com
 * @Date: 2024-04-24 08:35:55
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-06 17:59:51
 * @FilePath: \meimei-new\src\modules\auth\strategies\jwt.strategy.ts
 * @Description:
 *
 */
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from '../auth.service';
import { jwtConstants } from '../auth.constants';
import { Payload } from 'src/modules/login/login.interface';
import { Reflector } from '@nestjs/core';
import { PUBLIC_KEY } from 'src/common/contants/decorator.contant';
import { ExecutionContext } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly authService: AuthService,
    private readonly reflector: Reflector
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
      passReqToCallback: true, //设置回调的第一个参数是  request
    });
  }

  async validate(request: Request, payload: Payload) {
    // 如果没有payload，说明请求中没有token
    if (!payload) {
      return { userId: null }; // 返回一个基本的用户对象，让守卫处理认证逻辑
    }

    const { userId, pv } = payload;
    const authorization = (request.headers as any).authorization || '';
    if (!authorization) {
      return { userId: null };
    }
    const token = authorization.slice(7);
    if (!token) {
      return { userId: null };
    }

    try {
      const user = await this.authService.validateToken(userId, pv, token);
      return user || { userId };
    } catch (error) {
      return { userId: null }; // 即使token验证失败也返回基本用户对象
    }
  }
}
